<template>
    <section class="page-pd com-list">
        <div class="full" v-show="!isSubRouter">
            <div class="search-form">
                <search-form v-if="ready" :params="params" :formName="formName" :pageType="searchFormPageType"
                             @on-search="search"></search-form>
            </div>

            <div class="grid-top-bar">
                <el-button type="primary" v-if="parentIdReady && showActionAdd" size="small" @click="addItem"><span
                        class="bold el-icon-plus"></span> {{actionAddText}}
                </el-button>
                <el-button type="primary" v-if="!isDistrict && showActionEdit" size="small" @click="editItem"><span
                        class="bold el-icon-plus"></span> {{actionEditText}}
                </el-button>
                <el-button type="primary" v-if="!isDistrict && showActionDepartment" size="small" @click="department"><span
                        class="bold el-icon-plus"></span> 编辑内设机构
                </el-button>
                <template v-if="needReorder">
                    <el-button v-if="!isSorting" type="primary" plain size="small"
                               @click="loadForSort">{{fgTexts.reorder || '调整排序'}}
                    </el-button>
                    <template v-else>
                        <el-button type="primary" size="small" @click="saveSort">{{fgTexts.save || '保存'}}
                        </el-button>
                        <el-button size="small" @click="stopSortAndReload">{{fgTexts.cancel || '取消'}}
                        </el-button>
                    </template>
                </template>
                <div class="mglr-10" v-if="dataList.length">共计<span class="primay-color">{{total}}</span>个{{fgObjTitle}}
                </div>

                <div class="t-right tbar-right">
                    <el-dropdown @command="doBatAction" v-if="needImport || needExport" placement="bottom-start">
                        <el-button>{{fgTexts.batImExport || '批量导入/导出'}}<i
                                class="el-icon-arrow-down el-icon--right"></i>
                        </el-button>

                        <el-dropdown-menu slot="dropdown" class="drop-bat">
                            <el-dropdown-item v-if="needImport" command="Import">批量导入</el-dropdown-item>
                            <el-dropdown-item v-if="needExport" command="Export">批量导出</el-dropdown-item>
                            <el-dropdown-item v-if="needImport || needExport">
                                <div @click="toExportList">导入/导出详情</div>
                            </el-dropdown-item>
                        </el-dropdown-menu>
                    </el-dropdown>
                </div>
            </div>

            <table-view v-if="!refreshing" ref="table" :tablehead="tableHead"
                        :tabledata="dataList" :loading="loading"
                        stripe :filter="pageInfo" :auto-load="false"
                        :footSelectAll="true"
                        @selection-change="setSelect"
                        @on-load="loadList" :total="isSorting ? 0 : total" class="pager-square"
            >
                <div slot="handle_c" class="sort-handle"><i class="fio-shangxiatuodong"></i></div>
                <template v-for="col in slotCols">
                    <div :slot="col.slot" slot-scope="{row}" :key="col.slot">
                        {{formatDate(row[col.slot], col.format)}}
                    </div>
                </template>
                <section slot="operator" slot-scope="{row}" v-if="uiSet.rowActions.length">
                    <el-button v-for="action in getRowActions(row)" :key="action"
                               type="text" size="small" @click="doRowAction(action, row)">{{ActionTexts[action]}}
                    </el-button>
                </section>
                <div slot="footerLeft" class="bat-drop" v-if="dataList.length">
                    <el-dropdown @command="doBatAction" trigger="click" placement="bottom-start">
                        <el-button class="bat-button">{{fgTexts.batOperator || '批量操作'}}<i
                                class="el-icon-arrow-down el-icon--right"></i>
                        </el-button>

                        <el-dropdown-menu slot="dropdown" class="drop-bat">
                            <el-dropdown-item v-for="action in batActionsShow" :key="action"
                                              :command="action">{{ActionTexts[action]}}
                            </el-dropdown-item>
                        </el-dropdown-menu>
                    </el-dropdown>
                </div>
            </table-view>
            <slot></slot>
            <debug-info :info="uiSet" style="color:red"></debug-info>
        </div>
        <router-view v-if="isSubRouter" @listChanged="changeList" @importDone="onImportDone"></router-view>
    </section>
</template>

<script>
import BaseSearchForm from '../components/baseForm/search';
import formatDate from 'party_fe_component/src/utils/formatDate'
import tableView from 'party_fe_component/src/components/tableView'
import { DistrictIds, PageTypes, ActionTexts } from '../common/const';
import fg from 'flaginfojssdk';

export default {
    name: 'commonList',
    mixins: [
        require('../common/fgFormMixin').default,
        require('../common/sortMixin').default,
        require('../common/textConfigMixin').default,
    ],
    data() {
        return {
            params: {},
            isDistrict: false,
            showComponent: false,
            componentName: '',
            completeReady: false,
            configReady: false,
            parentIdReady: false,
            rootId: '', // 根组织id
            rootOrg: {},
            currentNodeId: '',
            parentNodeId: '',
            parentId: '', // 列表的上级组织id
            parentOrg: {},
            labelIdList: [],
            orgSelectedNodeDatas: [],
            pageInfo: {
                page: 1,
                pageSize: 10,
            },
            pageSizes: [10, 20, 30, 40, 50],

            searchData: {},
            dataList: [],
            loading: false,
            total: 0,

            tableHead: [],
            selectedRows: [],

            uiPage: {},
            needReorder: false,
            needCheckRow: false,
            needImport: false,
            needExport: false,

            ActionTexts,
        };
    },
    created() {
        this.loadFormName().then(t => {
            this.loadSceneConfigs(this.getPageName())
            this.loadUI()
        })
    },
    methods: {
        // { group_name: groupName, nature_of_group: natureOfGroup, subordination_relations: subordinationRelations }
        search(searchData) {
            this.searchData = searchData;
            this.stopSortAndReload(true);
        },
        // 用于文案加载
        getPageName() {
            return 'table' + this.formName
        },
        changeRoot(rootData) {
            this.rootOrg = rootData || {}
            this.rootId = rootData && rootData.id
            this.parentId = ''
            this.parentOrg = {}
        },
        checkIsDistrict() {
            let { labelIds, parentNodeId } = this;
            labelIds = labelIds || [];

            // 根节点
            if (parentNodeId === '0') {
                return true;
            }

            // 93, 117
            if (labelIds.length) {
                return DistrictIds.includes(labelIds[0]);
            }

            return false;
        },
        onNodeClick(data) {
            const { labelIds, labelIdList } = data;
            this.parentNodeId = data.parentId;
            this.currentNodeId = data.id;
            this.currentNodeName = data.name;
            this.parentId = data.id;
            this.parentOrg = data;
            this.labelIdList = labelIdList;
            this.labelIds = labelIds;
            this.isDistrict = this.checkIsDistrict();
            this.parentIdReady = true;
            if (this.formName) {
                this.pageInfo.page = 1
                this.searchData = {}
                this.stopSortAndReload()
            } else {
                this._needLoadList = true
            }

            this.setRequestParams(data.id);
        },
        setRequestParams(orgId) {
            const { labelIds } = this;
            if (labelIds && labelIds.length) {
                this.params = {
                    requestParams: {
            			url: '/orginfo/department',
            			method: 'get',
            			params: {
            				groupId: orgId,
            				orgLabel: labelIds[0]
            			}
                    }
                };
            }
        },
        loadUI() {
            this.loadUIPageCur(this.formName, PageTypes.Table).then(uiPage => {
                this.uiPage = uiPage

                var uiSet = this.uiSet
                if (uiSet.batActions) {
                    this.needReorder = uiSet.batActions.indexOf('Sort') > -1
                    this.needImport = uiSet.batActions.indexOf('Import') > -1
                    this.needExport = uiSet.batActions.indexOf('Export') > -1
                    this.needCheckRow = uiSet.batActions.length
                }
                this.pageInfo.pageSize = uiSet.pageSize || 10
                if (uiSet.pageSizes) this.pageSizes = uiSet.pageSizes

                this.initTableCols();

                this.configReady = true;

                /*IFDEBUG
                (uiSet.batActions || []).filter(a => a !== 'Sort').map(action => {
                    var method = '_bat' + action
                    if (!this[method]) console.error('缺少' + method + '方法')
                });
                (uiSet.rowActions || []).map(action => {
                    var method = '_row' + action
                    if (!this[method]) console.error('缺少' + method + '方法')
                })
                FIDEBUG*/
            })

            if (this._needLoadList) {
                this._needLoadList = false
                this.stopSortAndReload()
            }
        },
        showImExportMsg(isImport, onCancel) {
            /* eslint-disable-next-line */
            // <i class="el-icon-loading" style="font-size:40px;color:#666;margin-right:15px"></i>
            var h = this.$createElement
            var msg = (
                <div class="flex-center">
                    <span>{isImport ? '导入' : '导出'}</span><span>任务提交成功，您可到
                    </span><a class="primay-color" onClick={this.toExportList}>导入/导出详情</a>
                    <span>中查看结果</span>
                </div>
            )
            this.$x.confirm(msg, isImport ? '批量导入' : '批量导出', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                // iconClass: 'el-icon-loading',
            }).then(async t => {
                this.toExportList()
            }).catch(onCancel || this.$x.noop)
        },
        toExportList() {
            fg.goto('导入导出详情')
        },
        initTableCols() {
            const { mappingFields = {} } = this;
            var cols = this.uiSet.gridCols.map(({ title, width, field }) => {
                var col = {
                    label: title,
                    minWidth: width || 120,
                }
                if (field.format) {
                    col.slot = field
                } else {
                    col.prop = mappingFields[field] ? mappingFields[field] : field
                }
                return col
            })
            if (this.needCheckRow) {
                cols = [{ type: 'selection', minWidth: '60', width: '60', hidden: false }].concat(cols)
            }
            if (this.needReorder) {
                cols = [{
                    slot: 'handle_c',
                    label: '拖动',
                    minWidth: '60',
                    width: '60',
                    hidden: true,
                    props: { align: 'center' }, //其他属性
                }].concat(cols)
            }
            if (this.uiSet.rowActions && this.uiSet.rowActions.length > 0) {
                cols = cols.concat({ slot: 'operator', label: '操作', minWidth: this.uiSet.rowActions.length * 55 })
            }
            this.tableHead = cols
        },
        //以当前分页也查询条件刷新
        loadList(isSearch) {
            return this.loadListBy(this.pageInfo, this.searchData, typeof isSearch === 'boolean' ? isSearch : false)
        },
        doRowAction(action, row) {
            this['_row' + action](row)
        },
        _rowDelete(row) {
            this._batBatDelete([row])
        },
        setSelect(val) {
            this.selectedRows = val
        },
        doBatAction(action) {
            if (this.selectedRows.length === 0 && this.batNeedSelect(action)) {
                return this.$x.toast.warning(this.fgTexts.selectRows || '请选择数据行')
            }
            this['_bat' + action](this.selectedRows)
        },
        formatDate,
        saveSort() {
            //虚方法，子类实现
        },
        addItem() {
            //虚方法，子类实现
        },
        editItem() {
            //虚方法，子类实现
        },
        department() {
            //虚方法，子类实现
        },
        //根据行数据显示按钮。子类可覆盖
        getRowActions(row) {
            return this.uiSet.rowActions
        },
        batNeedSelect(action) {
            return ['Sort', 'Import', 'Export'].indexOf(action) === -1
        },
        //新增或编辑后刷新
        changeList() {
            this.loadList()
        },
        onImportDone() {
            this.showImExportMsg(true, t => {
                this.$router.back()
                this.loadList()
            })
        },
        showRowOutAction(action) {
            const { rowOutActions = [] } = this.uiSet || {};
            return rowOutActions.includes(action);
        }
    },
    computed: {
        // formName() {
        //     return this.$route.query.formName
        // },
        ready() {
            return this.formName && this.searchFormPageType;
        },
        uiSet() {
            return this.uiPage.ui
        },
        slotCols() {
            return this.tableHead.filter(col => col.slot && col.slot !== 'handle_c')
        },
        batActionsShow() {
            return this.uiSet && this.uiSet.batActions.filter(this.batNeedSelect)
        },
        isSubRouter() {
            // 子类实现
            return false
        },
        fgObjTitle() {
            // 子类实现
            return ''
        },
        showActionEdit() {
            // 子类实现
            return false;
        },
        showActionAdd() {
            // 子类实现
            return false;
        },
        showActionDepartment() {
            // 子类实现
            return false;
        },
        actionAddText() {
            //子类可覆盖
            return '新建' + this.fgObjTitle
        },
    },
    components: { tableView, SearchForm: BaseSearchForm },
}
</script>

<style scoped lang="scss">
    @import "../../css/defines";

    .com-list {
        overflow: auto;
    }

    .sort-handle {
        cursor: ns-resize;
        display: inline-block;
        vertical-align: middle;
    }

    .bat-drop {
        cursor: pointer;
    }

    .drop-bat {
        min-width: 110px;
    }

    .bat-button {
        padding: 7px 20px;
    }

    .grid-top-bar {
        display: flex;
        flex-flow: nowrap;
        padding: 30px 0 20px;
    }

    .mglr-10 {
        line-height: 32px;
        margin: 0 10px;
    }

    .tbar-right {
        flex: 1;
    }

    .tree-head {
        line-height: 60px;
        font-size: 14px;
        padding-left: 20px;
        border-bottom: 1px solid #EAEAEA;

        /deep/ + * .search {
            padding: 15px 20px;
        }
    }

    /*.th-ellipsis {*/
        /*/deep/ th .cell {*/
            /*white-space: nowrap;*/
            /*overflow: hidden;*/
            /*text-overflow: ellipsis;*/
        /*}*/
    /*}*/
</style>
